package com.petter.rabbitmq.publish;

import com.petter.rabbitmq.work.Producer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/**
 * @author : GD
 * @date :2022/3/10 : 22:11
 */
public class PublishConsumer {

    public static void main(String[] args) throws Exception{
        // 1. 获取链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        // 2. 通过工厂获取连接
        Connection connection = factory.newConnection();
        // 3. 通过连接获取channel
        Channel channel = connection.createChannel();
        // 4. channel 申明declare 一个队列
        channel.queueDeclare(PublishProducer.QUEUE_NAME,true,false,false,null);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        // 5. 队列消费
        channel.basicConsume(PublishProducer.QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }
}
